package memberlayer

import (
    "errors"
	//"strconv"
	"dhfshop/utils/math"
	//"dhfshop/models/shopping"
	"dhfshop/models/member"
	//"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego"
)

// 增加余额
func AddBalance(partnerId,memberId int64,srcAccount *member.Account,value,gift float32,tradeNo string,status int) (logId int64, err error) {
	srcBalace := srcAccount.Balance
	srcPresent := srcAccount.Present
	srcAccount.Balance += value
	dstBalace := srcAccount.Balance
	if gift > 0 {
	    srcAccount.Present += gift
	    srcAccount.TotalPresent += gift
		if err = member.UpdateAccountById(srcAccount, "balance", "present", "total_present"); err != nil {
			beego.Debug(err.Error())
			return
		}
	} else {
	    if err = member.UpdateAccountById(srcAccount, "balance"); err != nil {
			beego.Debug(err.Error())
			return
		}
	}
	log := &member.BalanceLog{
		PartnerId:    partnerId,
		MemberId:     memberId,
		BusinessKind: 2,
		Title:        "增加余额",
		OuterNo:      tradeNo,
		InOutType:    1,
		SrcBalance:   srcBalace,
		IncBalance:   value,
		DstBalance:   dstBalace,
		Present:      gift,
        SrcPresent:   srcPresent,
		IncPresent:   gift,
		DstPresent:   srcPresent + gift,
		State:        status,
		RelateUser:   0,
	}
	if logId, err = member.AddBalanceLog(log); err != nil {
	    beego.Debug(err.Error())
	}
	return
}

// 需要把赠送金额(营销费用)摊薄到每笔扣款中
func DiscountBalance(partnerId,memberId int64,srcAccount *member.Account,fee float32,outerNo string) (logId int64, err error) {
	if srcAccount.Balance + srcAccount.Present < fee {
		err = errors.New(ErrAccountNotEnoughAmount.Error())
		return
	}
	payRate := srcAccount.Balance/(srcAccount.Balance + srcAccount.Present)
	payBalance := math.MultiFloat32Price(fee, payRate)
	payPresent := math.SubPrice(fee, payBalance)
	srcBalace := srcAccount.Balance
	srcPresent := srcAccount.Present
	srcAccount.Balance = math.SubPrice(srcBalace, payBalance)
	srcAccount.Present = math.SubPrice(srcPresent, payPresent)
	if err = member.UpdateAccountById(srcAccount, "balance", "present"); err != nil {
		beego.Debug(err.Error())
		return
	}
	log := &member.BalanceLog{
		PartnerId:    partnerId,
		MemberId:     memberId,
		BusinessKind: 3,
		Title:        "扣减余额",
		OuterNo:      outerNo,
		InOutType:    0,
		SrcBalance:   srcBalace,
		IncBalance:   payBalance,
		DstBalance:   srcAccount.Balance,
		Present:      payPresent,
		SrcPresent:   srcPresent,
		IncPresent:   payPresent,
		DstPresent:   srcAccount.Present,
		State:        1,
		RelateUser:   0,
	}
	if logId, err = member.AddBalanceLog(log); err != nil {
		beego.Debug(err.Error())
	}
	return
}

